package com.tscnd.core.web.controller.login;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tscnd.core.entity.user.User;
import com.tscnd.core.exception.CheckException;
import com.tscnd.core.service.user.IUserService;
import com.tscnd.core.utils.EncryptTools;
import com.tscnd.core.utils.SecurityCode;
import com.tscnd.core.utils.SecurityCode.SecurityCodeLevel;
import com.tscnd.core.utils.SecurityImage;
import com.tscnd.core.web.Constants;

@Controller
@RequestMapping("secure")
public class LoginController {
	
	private final static Logger LOGGER = Logger.getLogger(LoginController.class);
	
	@Autowired
	private IUserService userService;
	
	/**
	 * 跳转到登录页面
	 * @return
	 */
	@RequestMapping(value="tologin.htm", method = RequestMethod.GET)
	public String tologin(){
		return "login/login";
	}
	
	
	/**
	 * 登录验证
	 * @param resMap
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="login.do",method=RequestMethod.POST)
	private Map<String,Object> login(@RequestParam Map<String,String> resMap,
			HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> resultMap=new HashMap<String,Object>();
		try{
			checkParam(resMap);
			String j_validateCode=resMap.get(Constants.J_VERIFY_CODE);
			String j_password=resMap.get(Constants.J_PASSWORD);
			String j_username=resMap.get(Constants.J_USERNAME);
			//从session中取出验证码 
			String validateCode=(String) request.getSession().getAttribute(Constants.J_VERIFY_CODE);
			//刷新验证码防止暴力破解
			request.getSession().setAttribute(Constants.J_VERIFY_CODE, 
					SecurityCode.getSecurityCode(Constants.VERIF_FOUR_CODE,SecurityCodeLevel.Simple, true));
			if(!validateCode.equals(j_validateCode)){
				throw new CheckException("eor_0032","verification code must be filled");
			}
			//查询用户对象
			User user=userService.findUserByUsernmae(j_username);
			if(user==null){
				throw new CheckException("eor_0022","Username or password is incorrect");
			}
			String password=user.getPassword();
			if(StringUtils.isNotEmpty(password)){
				password = EncryptTools.MD5(EncryptTools.MD5(password+j_username,32)+j_validateCode,32);
				if(j_password.equals(password)){
					resultMap.put(Constants.MESSAGE, true);
					//登录成功用户名放进session中 
					request.getSession().setAttribute(Constants.J_USERNAME, user);
				}else{
					throw new CheckException("eor_0022","Username or password is incorrect");
				}
			}
		}catch(CheckException e){
			LOGGER.error("登录异常【"+e.getErrorCode()+"】："+e.getMessage());
			resultMap.put(Constants.MESSAGE, e.getErrorCode());
		}catch(Exception e){
			LOGGER.error("登录异常【eor_000】："+e.getMessage());
			resultMap.put(Constants.MESSAGE, "eor_000");
		}  
		return resultMap;
	}
	
	
	/**
	 * 检查登录请求参数
	 * @param resMap
	 * @throws CheckException 
	 */

	private  void checkParam(Map<String,String> resMap) throws CheckException{
		if(resMap==null){
			throw new CheckException("eor_0001","Logon request object is empty");
		}
		
		if(StringUtils.isEmpty(resMap.get(Constants.J_USERNAME))||StringUtils.isEmpty(resMap.get(Constants.J_PASSWORD))){
			throw new CheckException("eor_0002","Username and password can not be empty");
		}
		
		if(StringUtils.isEmpty(resMap.get(Constants.J_VERIFY_CODE))){
			throw new CheckException("eor_0003","verification code must be filled");
		}
	}
	
	/**
	 *  前端展示验证码
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "cjpge.jpg", method = RequestMethod.GET)
	public void toCjpge(HttpServletRequest request, HttpServletResponse response) {
		response.setContentType("image/jpeg");
		String validateCode = SecurityCode.getSecurityCode(Constants.VERIF_FOUR_CODE,SecurityCodeLevel.Simple, true);
		request.getSession().setAttribute(Constants.J_VERIFY_CODE, validateCode);
		ByteArrayInputStream arrayInputStream = SecurityImage
					.getImageAsInputStream(validateCode);
		OutputStream outputStream = null;
		try {
			response.reset();
			outputStream = new BufferedOutputStream(response.getOutputStream());
			byte[] buffer = new byte[4096];
			int len = 0;
				// 写入输出流
				while ((len = arrayInputStream.read(buffer, 0, buffer.length)) != -1) {
					outputStream.write(buffer, 0, len);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				try {
					if (arrayInputStream != null) {
						arrayInputStream.close();
					}
					arrayInputStream = null;// 清空流
					if (outputStream != null) {
						outputStream.close();
					}
					outputStream = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
	}
}
